﻿var viewModel = new function () {
    // Configs
    this.Accounts = ko.observableArray(data.ListUser);
    this.PageSize = ko.observable(data.Paging.PageSize);
    this.CurrentPageIndex = ko.observable(data.Paging.PageIndex);
    this.MaxPageIndex = ko.observable(data.Paging.TotalPages);
    this.ColName = ko.observable("CreationDate");
    this.SortOrder = ko.observable("desc");
    this.Keywords = ko.observable("Keywords");

    // Total Records
    this.TotalLead = ko.observable(data.Paging.TotalRecords);
    this.PageText = ko.computed(function () {
        var total = this.TotalLead();
        if (total == 1)
            return total + " tài khoản";
        else
            return total + " tài khoản";

    }, this);



    this.PageSizeText = ko.computed(function () {
        var pagevalue = this.PageSize().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);
        if (!IsNumeric(pagevalue))
            return "* Nhập một số giữa 1 - 100";
        else if (pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return "* Nhập một số giữa 1 - 100";
        }
        else {
            return "";
        }

    }, this);
    this.PageCurrentText = ko.computed(function () {
        var pagecurrent = parseInt(this.CurrentPageIndex());
        var pagesize = parseInt(pagecurrent, 10);

        if (!IsNumeric(this.CurrentPageIndex()))
            return "* Nhập một số giữa 1 - " + this.MaxPageIndex() + " ";
        else if (pagecurrent.toString() == 'NaN' || !IsNumeric(pagecurrent) || pagecurrent < 1 || pagecurrent > this.MaxPageIndex()) {
            return "* Nhập một số giữa 1 - " + this.MaxPageIndex() + " ";
        }
        else {
            return "";
        }

    }, this);

    // Paginate
    this.PrevPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            this.CurrentPageIndex(page - 1);
            LoadDataFromServer();
        }
    }
    this.PrevButtonClass = ko.computed(function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page > 1) {
            return "btn btn-prev-arrow prev-active";
        }
        else {
            return "btn btn-prev-arrow";
        }
    }, this);

    this.NextPage = function () {
        var page = parseInt(this.CurrentPageIndex());
        if (page < this.MaxPageIndex()) {
            this.CurrentPageIndex(page + 1);
            LoadDataFromServer();
        }
    }
    this.NextButtonClass = ko.computed(function () {
        if (this.CurrentPageIndex() == this.MaxPageIndex() || this.MaxPageIndex() == 1)
            return "btn btn-next-arrow next-disabled";
        else
            return "btn btn-next-arrow";
    }, this);

    // Load data
    function LoadDataFromServer() {
        var pagevalue = viewModel.PageSize().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);
        if (pagesize.toString() == 'NaN' || !IsNumeric(pagesize) || pagesize < 1 || pagesize > 100) {
            viewModel.PageSize(data.PageSize);
        }

        pagevalue = viewModel.CurrentPageIndex().toString().replace(/\s/g, '');
        var pageindex = parseInt(pagevalue, 10);
        if (pageindex.toString() == 'NaN' || !IsNumeric(pageindex) || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
            viewModel.CurrentPageIndex(data.PageIndex);
        }

        var keywords = $('#searchKeyword').val();
        if (keywords == undefined || keywords == "Keywords")
            keywords = "";
        var url = "/Management/AccountList/GetData";
        url = url + "?keywords=" + keywords;
        url = url + "&pageSize=" + pagesize;
        url = url + "&pageIndex=" + pageindex;
        url = url + "&sortby=" + viewModel.ColName();
        url = url + "&sortorder=" + viewModel.SortOrder();

        // Json Get function to retrive data from server
        $.getJSON(url, function (data) {
            viewModel.CurrentPageIndex(data.Paging.PageIndex);
            viewModel.MaxPageIndex(data.Paging.TotalPages);
            viewModel.PageSize(data.Paging.PageSize);
            viewModel.TotalLead(data.Paging.TotalRecords);
            viewModel.Accounts(data.ListUser);
        });
    }

    // Search button
    this.SearchButton = function () {
        var pagevalue = viewModel.PageSize().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);
        if (pagesize.toString() == 'NaN' || !IsNumeric(pagesize) || pagesize < 1 || pagesize > 100) {
            viewModel.PageSize(data.PageSize);
        }

        pagevalue = viewModel.CurrentPageIndex().toString().replace(/\s/g, '');
        var pageindex = parseInt(pagevalue, 10);
        if (pageindex.toString() == 'NaN' || !IsNumeric(pageindex) || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
            viewModel.CurrentPageIndex(data.PageIndex);
        }

        var url = "/Management/AccountList/GetData";
        url = url + "?keywords=" + viewModel.Keywords();
        url = url + "&pageSize=" + pagesize;
        url = url + "&pageIndex=" + pageindex;
        url = url + "&sortby=" + viewModel.ColName();
        url = url + "&sortorder=" + viewModel.SortOrder();

        // Json Get function to retrive data from server
        $.getJSON(url, function (data) {
            viewModel.CurrentPageIndex(data.Paging.PageIndex);
            viewModel.MaxPageIndex(data.Paging.TotalPages);
            viewModel.PageSize(data.Paging.PageSize);
            viewModel.TotalLead(data.Paging.TotalRecords);
            viewModel.Accounts(data.ListUser);
        });
    };

    // Sort by Colum/Order
    function SetOrder(event, ColName) {
        if (this.ColName() === ColName) {
            this.SwitchSortOrder();
        } else {
            this.ColName(ColName);
            this.SortOrder("asc");
        }
        SetTHClass(ColName, event);
        LoadDataFromServer();
    }
    this.SetOrder = SetOrder; // Set to an knockout object
    function SwitchSortOrder() {
        if (this.SortOrder() === "asc") {
            this.SortOrder("desc");
        } else {
            this.SortOrder("asc");
        }
    }
    this.SwitchSortOrder = SwitchSortOrder;

    function SetTHClass(colName, event) {
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("asc");
        $("div.title").parent().find(".sort_wrapper").children("span").removeClass("desc");

        if (viewModel.SortOrder() === "asc") {
            $("#" + colName).children("span").addClass("asc");
        } else {
            $("#" + colName).children("span").addClass("desc");
        }
    }

    this.UserOption = ko.observable();
    this.UserOptions = ko.observableArray(data.UserFilter);

    // Delete view lead items
    this.LockAccount = function () {
        var pagevalue = viewModel.PageSize().toString().replace(/\s/g, '');
        var pagesize = parseInt(pagevalue, 10);
        if (pagesize.toString() == 'NaN' || !IsNumeric(pagesize) || pagesize < 1 || pagesize > 100) {
            viewModel.PageSize(data.PageSize);
            return false;
        }

        pagevalue = viewModel.CurrentPageIndex().toString().replace(/\s/g, '');
        var pageindex = parseInt(pagevalue, 10);
        if (pageindex.toString() == 'NaN' || !IsNumeric(pageindex) || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
            viewModel.CurrentPageIndex(data.PageIndex);
            return false;
        }

        var userId = $('#accountId').val();

        var url = "/Management/AccountList/Locked";
        url = url + "?keywords=" + viewModel.Keywords();
        url = url + "&pageSize=" + pagesize;
        url = url + "&pageIndex=" + pageindex;
        url = url + "&sortby=" + viewModel.ColName();
        url = url + "&sortorder=" + viewModel.SortOrder();
        url = url + "&id=" + userId;

        // Append message waiting
        $('#processing').html("<font color='read'>Đang cập nhật tài khoản...</font>");

        // Json Get function to retrive data from server
        $.getJSON(url, function (data) {
            if (data != null && data != undefined) {

                viewModel.CurrentPageIndex(data.Paging.PageIndex);
                viewModel.MaxPageIndex(data.Paging.TotalPages);
                viewModel.PageSize(data.Paging.PageSize);
                viewModel.TotalLead(data.Paging.TotalRecords);
                viewModel.Accounts(data.ListUser);

                // Close message waiting
                $.fancybox.close();
                $('#processing').html("");
            }
        });
    };

    // PageSize/ PageCurrent keypress enter
    this.RunSomethingKey = function (viewModel, event) {
        if (event.keyCode == 13 || event.keyCode == 9) {
            this.RunSomething(viewModel, event);
        }
        return true;
    }
    this.RunSomething = function (viewModel, event) {
        LoadDataKeyPresss();
    }
    function LoadDataKeyPresss() {
        // Page Size
        var pageSizeValue = $('#pagesize').val().toString().replace(/\s/g, '');
        var pagesize = parseInt(pageSizeValue, 10);
        if (!IsNumeric(pageSizeValue) || pagesize.toString() == 'NaN' || pagesize < 1 || pagesize > 100) {
            return false;
        }

        // Page Index
        var pageIndexValue = $('#pagecurrent').val().toString().replace(/\s/g, '');
        var pageindex = parseInt(pageIndexValue, 10);
        if (!IsNumeric(pageIndexValue) || pageindex.toString() == NaN || pageindex < 1 || pageindex > viewModel.MaxPageIndex()) {
            return false;
        }
        
        var keywords = $('#searchKeyword').val();
        if (keywords == undefined || keywords == "Keywords")
            keywords = "";
        var url = "/Management/AccountList/GetData";
        url = url + "?keywords=" + keywords;
        url = url + "&pageSize=" + pagesize;
        url = url + "&pageIndex=" + pageindex;
        url = url + "&sortby=" + viewModel.ColName();
        url = url + "&sortorder=" + viewModel.SortOrder();

        // Json Get function to retrive data from server
        $.getJSON(url, function (data) {
            viewModel.CurrentPageIndex(data.Paging.PageIndex);
            viewModel.MaxPageIndex(data.Paging.TotalPages);
            viewModel.PageSize(data.Paging.PageSize);
            viewModel.TotalLead(data.Paging.TotalRecords);
            viewModel.Accounts(data.ListUser);
        });
    }
};

ko.applyBindings(viewModel, document.getElementById("main"));

// Extend functions
function OpenUserPreview(id) {
    // Set hidden value
    $('#userID').val(id);

    // Call an ajax get method
    var url = "/Management/AccountList/GetUserPerview";
    url = url + "?id=" + id;

    // Json Get function to retrive data from server
    $.getJSON(url, function (data) {
        if (data != null && data != undefined) {
            $("#vwFullname").text(data.Fullname);
            $("#vwEmail").text(data.Email);
            $("#vwFirstName").text(data.FirstName);
            $("#vwLastName").text(data.LastName);
            $("#vwCreationDate").text(data.CreationDate);
            $("#vwAddress").text(data.Address);
            $("#vwCity").text(data.City);
            $("#vwState").text(data.State);
            $("#vwApproved").text(data.IsApproved);
            $("#vwNumLogin").text(data.NumLogin);
            $("#vwLastLoginDate").text(data.LastLoginDate);
            $("#vwLockedOut").text(data.IsLockedOut);
            $("#vwLastLockedOutDate").text(data.LastLockedOutDate);
        }
    });
}

function OpenAccount(id) {
    $('#accountId').val(id);
    $('#fullname').text($('#account' + id).attr("rel"));
    $('#status').text($('#status' + id).text());
}